'use strict';
/**
 * This is a special component that wraps around other component to apply authenticate methods
 */
var React = require('react');
var LoginStore = require('../stores/login');

module.exports = function(ComposedComponent) {
	return React.createClass({
		static: {
			willTransitionTo: function(transition) {
				if (!LoginStore.isLoggedIn()) {
					transition.redirect('/login' , {} , {'nextPath' : transition.path});
				}
			}
		},
		getInitialState: function() {
			return this._getLoginState();
		},
		_getLoginState: function() {
			return {
				userLoggedIn: LoginStore.isLoggedIn(),
				user: LoginStore.user,
				jwt: LoginStore.jwt
			};
		},
		componentDidMount: function() {
			LoginStore.addChangeListener(this._onChange);
		},
		_onChange: function() {
			this.setState(this._getLoginState());
		},
		componentWillMount: function() {
			LoginStore.removeChangeListener(this._onChange);
		},
		render: function() {
			return (
				<ComposedComponent
        			{...this.props}
        			user={this.state.user}
        			jwt={this.state.jwt}
        			userLoggedIn={this.state.userLoggedIn} />
			);
		}
	});
};
